package com.firemoss.atonement.mapper.resolution
{
	import flash.utils.Dictionary;
	import mx.collections.IList;
	import org.as3commons.reflect.Type;

	/**
	 * Default value resolver.  IList and Dictionary resolution
	 * is passed to the ListValueResolver and DictionaryValueResolver, and all
	 * other types are passed to the SimpleAssignmentValueResolver (which just returns
	 * its passed value).
	 */
	public class DefaultValueResolverFactory implements IValueResolverFactory
	{

		//----------------------------------------------------------
		// Private Properties 
		//----------------------------------------------------------

		private var arrayResolver : ArrayValueResolver = new ArrayValueResolver();
		private var dictionaryResolver : DictionaryValueResolver = new DictionaryValueResolver();
		private var listResolver : ListValueResolver = new ListValueResolver();
		private var simpleAssignmentValueResolver : SimpleAssignmentValueResolver = new SimpleAssignmentValueResolver();

		//----------------------------------------------------------
		// Public Methods 
		//----------------------------------------------------------

		public function canResolveDifferentTypes( type1 : Type, type2 : Type ) : Boolean
		{

			if ( new type1.clazz() is IList && new type2.clazz() is Array )
			{
				return true;
			}
			if ( new type1.clazz() is Array && new type2.clazz() is IList )
			{
				return true;
			}

			return false
		}

		public function create( type : Type, targetType : Type ) : IValueResolver
		{

			try
			{
				var sourceInstance : Object = new type.clazz()
				var targetInstance : Object = new targetType.clazz()

				if ( sourceInstance is IList )
				{
					if ( targetInstance is Array )
					{
						return arrayResolver
					}
					else
					{
						return listResolver
					}
				}

				if ( sourceInstance is Array )
				{
					if ( targetInstance is IList )
					{
						return listResolver
					}
					else
					{
						return arrayResolver
					}
				}

				if ( targetInstance is Dictionary )
				{
					return dictionaryResolver;
				}
			}
			catch ( e : Error )
			{
				return simpleAssignmentValueResolver
			}

			return simpleAssignmentValueResolver;
		}
	}
}
